package com.example.piece.ui.activity

import android.content.pm.ActivityInfo
import android.graphics.Rect
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView


import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.base.BaseApp.Companion.context
import com.example.base.ext.getViewModel
import com.example.base.tools.JsonTool
import com.example.base.ui.activity.BaseActivity
import com.example.base.ui.fragment.BaseFragment
import com.example.base.vm.onError
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.Key.DataKey.TARGET_USER_ID
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityDetailBinding
import com.example.piece.databinding.ItemHomeRecommendationVideoBinding
import com.example.piece.entity.AttentionEntity
import com.example.piece.entity.UserMessageSystemEntity
import com.example.piece.tools.UtilsPlay
import com.example.piece.ui.adapter.HomeRecommendationAdapter
import com.example.piece.ui.adapter.ViewPagerAdapter
import com.example.piece.ui.fragment.*
import com.example.piece.vm.HelperViewModel
import com.example.piece.vm.HomeViewModel
import com.example.piece.vm.JokesViewModel
import com.example.piece.vm.UserViewModel
import com.kongzue.dialogx.dialogs.TipDialog
import com.therouter.router.Autowired
import com.therouter.router.Route
import com.wenming.library.encryption.imp.AESEncode
import xyz.doikki.videocontroller.StandardVideoController
import xyz.doikki.videocontroller.component.*
import xyz.doikki.videoplayer.player.AbstractPlayer
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.player.VideoViewManager

/**
 * 详情
 */
@Route(path = RoutePath.MAIN_DETAIL_ACTIVITY)
class DetailActivity : Layer3Activity<ActivityDetailBinding, ViewDataBinding>() {

    companion object {
        /**
         * 当前播放的位置
         */
        protected var mCurPos = -1

        /**
         * 上次播放的位置，用于页面切回来之后恢复播放
         */
        protected var mLastPos = mCurPos
        protected var mVideoView: VideoView<AbstractPlayer>? = null
        protected var mController: StandardVideoController? = null
        protected var mErrorView: ErrorView? = null
        protected var mCompleteView: CompleteView? = null
        protected var mTitleView: TitleView? = null
        var mCurrentIndex = 0
    }

    override val title: String
        get() = H5_TITLE

    override val isTransparentStatusBar: Boolean = true
    override val isLockPortrait: Boolean = true
    override val statusBarAlpha: Int = 0
    override val isDarkMode: Boolean = true
    override val isFitsSystemWindows: Boolean = true
    override val leftIcon1Res: Int = R.drawable.ic_back


    private val userViewModel: UserViewModel by lazy {
        getViewModel<UserViewModel>()
    }
    private val jokesViewModel: JokesViewModel by lazy {
        getViewModel<JokesViewModel>()
    }
    private val homeViewModel: HomeViewModel by lazy {
        getViewModel<HomeViewModel>()
    }
    private val helperViewModel: HelperViewModel by lazy {
        getViewModel<HelperViewModel>()
    }

    /**  类型 Adapter  **/
    private val homeRecommendationAdapter: HomeRecommendationAdapter by lazy {
        val adapter = HomeRecommendationAdapter(emptyList(),
            userViewModel,
            jokesViewModel,
            helperViewModel,
            this as BaseActivity<ViewDataBinding>, false,false)
        mCenterViewBinding?.rv?.adapter = adapter
        adapter
    }

    override fun onClickLeftIcon1(view: View) {
        onBackPressed()

    }

    @JvmField
    @Autowired(name = Key.DataKey.H5_TITLE)
    var H5_TITLE: String = ""

    @JvmField
    @Autowired(name = Key.DataKey.ITEM_DETAIL)
    var ITEM_DETAIL: String = ""
    lateinit var entity: AttentionEntity

    override val centerLayoutRes: Int
        get() = R.layout.activity_detail

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)


        entity =
            JsonTool.parseObject<AttentionEntity>(ITEM_DETAIL, AttentionEntity::class.java)

        val mutableListOf = mutableListOf<AttentionEntity>()
        mutableListOf.add(entity)
        homeRecommendationAdapter.setList(mutableListOf)

        //初始化 ViewPager
        initViewPager()

        //初始化播放器
        initVideoView()

        homeRecommendationAdapter.setOnItemChildClickListener(object : OnItemChildClickListener {
            override fun onItemChildClick(
                adapter: BaseQuickAdapter<*, *>,
                view: View,
                position: Int,
            ) {
                startPlay(position)
            }
        }
        )

        mCenterViewBinding?.rv?.addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {

            }

            override fun onChildViewDetachedFromWindow(view: View) {
                val playerContainer = view.findViewById<FrameLayout>(R.id.player_container)
                val v = playerContainer?.getChildAt(0)
                if (v != null && v === mVideoView && mVideoView?.isFullScreen() != true) {
                    releaseVideoView()
                }
            }

        })

    }

    private fun initViewPager() {
        val titles = arrayListOf<String>("评论", "点赞")
        val fragments = mutableListOf<Fragment>()
        fragments.add(PingLun0Fragment.newInstance(entity.joke.jokesId))
        fragments.add(DianZanFragment.newInstance(entity.joke.jokesId))

        mCenterViewBinding?.vp?.adapter =
            ViewPagerAdapter(supportFragmentManager, fragments, titles)
        mCenterViewBinding?.tab?.setupWithViewPager(mCenterViewBinding?.vp)
        mCenterViewBinding?.vp?.offscreenPageLimit = 5

    }


    private fun autoPlayVideo(recyclerview: RecyclerView?) {
        recyclerview?.let {
            val childCount = it.childCount
            loop@ for (i in 0 until childCount) {
                val itemView = it.getChildAt(i)

                var binding =
                    DataBindingUtil.getBinding<ViewDataBinding>(itemView)
                if (binding is ItemHomeRecommendationVideoBinding) {
                    val rect = Rect()
                    binding?.playerContainer?.getLocalVisibleRect(rect)
                    val height = binding?.playerContainer?.height
                    if (rect.top === 0 && rect.bottom === height) {
                        binding?.position?.let { it1 -> startPlay(it1) }
                        return
                    }
                }

            }

        }

    }

    protected fun initVideoView() {
        mVideoView = context?.let { VideoView<AbstractPlayer>(it) }
        mVideoView?.setOnStateChangeListener(object : VideoView.SimpleOnStateChangeListener() {
            override fun onPlayStateChanged(playState: Int) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    UtilsPlay.removeViewFormParent(mVideoView)
                    mLastPos = mCurPos
                    mCurPos = -1
                }
            }
        })
        mController = context?.let { StandardVideoController(it) }
        mErrorView = ErrorView(this)
        mController?.addControlComponent(mErrorView)
        mCompleteView = context?.let { CompleteView(it) }
        mController?.addControlComponent(mCompleteView)
        mTitleView = context?.let { TitleView(it) }
        mController?.addControlComponent(mTitleView)
        mController?.addControlComponent(context?.let { VodControlView(it) })
        mController?.addControlComponent(context?.let { GestureView(it) })
        mController?.setEnableOrientation(true)
        mVideoView?.setVideoController(mController)
    }

    private fun startPlay(position: Int) {
        if (mCurPos == position) return
        if (mCurPos != -1) {
            releaseVideoView()
        }
        val videoBean: AttentionEntity = homeRecommendationAdapter.data[position]
        if (videoBean.joke.type.toInt() < 3) {
            return

        }
        //边播边存
//        String proxyUrl = ProxyVideoCacheManager.getProxy(getActivity()).getProxyUrl(videoBean.getUrl());
//        mVideoView.setUrl(proxyUrl);
        val videoUrl =
            AESEncode.Decrypt(
                videoBean?.joke?.videoUrl?.split(",")?.get(0)?.replace("ftp://", "").toString()
                    .trim(),
                "cretinzp**273846"
            )
        mVideoView?.setLooping(true)

        mVideoView?.setUrl(videoUrl)

        Log.e("dddddddddddddvideoUrl", videoUrl + "")

        mTitleView?.setTitle(videoBean.joke.videoTime)
        val itemView: View =
            mCenterViewBinding?.rv?.layoutManager?.findViewByPosition(position) ?: return
        val viewHolder =
            DataBindingUtil.getBinding<ItemHomeRecommendationVideoBinding>(itemView)
        //把列表中预置的PrepareView添加到控制器中，注意isDissociate此处只能为true, 请点进去看isDissociate的解释
        mController?.addControlComponent(viewHolder?.prepareView, true)
        UtilsPlay.removeViewFormParent(mVideoView)
        viewHolder?.playerContainer?.addView(mVideoView, 0)
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        getVideoViewManager()?.add(mVideoView, Key.DataKey.HOME_LIST)
        mVideoView?.start()
        mCurPos = position
    }

    private fun releaseVideoView() {
        mVideoView?.release()
        if (mVideoView?.isFullScreen() == true) {
            mVideoView?.stopFullScreen()
        }
        if (this?.requestedOrientation !== ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            this?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        mCurPos = -1
    }

    /**
     * 子类可通过此方法直接拿到VideoViewManager
     */
    protected fun getVideoViewManager(): VideoViewManager? {
        return VideoViewManager.instance()
    }

    override fun onPause() {
        super.onPause()
        pause()
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected fun pause() {
        releaseVideoView()
    }

    override fun onResume() {
        super.onResume()
        resume()
    }


    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    protected fun resume() {
        if (mLastPos == -1) return
        if (mCurrentIndex !== 1) return
        //恢复上次播放的位置
        startPlay(mLastPos)
    }
}